// pages/mine/mine.js
import {
	createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
	store
} from '../../store/store'
import wrapRequest from '../../utils/request'
const shareUtils = require('../../utils/share')
var app = getApp()

Page({
	data: {
		defaultAvatarUrl: 'https://cdn-we-retail.ym.tencent.com/miniapp/usercenter/icon-user-center-avatar@2x.png',
		defaultNick: "微信用户"
	},
	// 事件处理函数
	onLoad(options) {
		this.storeBindings = createStoreBindings(this, {
			store,
			fields: ['userInfo'],
			actions: ['updateUserInfo'],
		})
	},
	onUnload() {
		this.storeBindings.destroyStoreBindings()
	},
	onShow() {
		console.log("onShow")
	},
	getUserInfo() {
		console.log('getUser:', this.data.userInfo)
	},
	onChooseAvatar(e) {
		var that = this
		let avatar = e.detail.avatarUrl
		console.log('avatar:', avatar)
		wx.uploadFile({
			filePath: avatar,
			name: 'file',
			url: app.globalData.uploadDomain + '/file/upload',
			success: function (res) {
				const jsonData = JSON.parse(res.data)
				const uploadAvatar = jsonData.data?.url
				if (uploadAvatar.length > 0) {
					avatar = uploadAvatar
				}
				console.log('avatar', avatar)
			},
			fail: function (res) {
				console.log('upload fail :', res)
			},
			complete: function (res) {
				wrapRequest('/v1.0/user/update', 'POST', {
					data: {
						id: that.data.userInfo.id,
						avatar: avatar,
					},
					success: function (res) {
						that.updateUserInfo({
							"id": that.data.userInfo.id,
							"nick": that.data.userInfo.nick,
							"avatar": avatar,
						})
					},
					fail: function (e) {
						console.log('http fail:', e)
					}
				})
			}
		})

	},
	onInputChange(e) {
		var that = this
		const nick = e.detail.value
		wrapRequest('/v1.0/user/update', 'POST', {
			data: {
				id: that.data.userInfo.id,
				nick: nick,
			},
			success: function (res) {
				that.updateUserInfo({
					"id": that.data.userInfo.id,
					"avatar": that.data.userInfo.avatar,
					"nick": nick,
				})
			},
			fail: function (e) {
				console.log('http fail:', e)
			}
		})
	},
	navigateTo(e) {
		const url = e.currentTarget.dataset.url
		wx.navigateTo({
			url: url,
		})
	},
	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {
		return shareUtils.getShareConfig();
	},
	onShareTimeline() {
		return shareUtils.getShareConfig();
	}
})